package com.alpesressources.comexpert.bo.adapter;

import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

import com.alpesressources.comexpert.bo.request.Request;
import com.alpesressources.comexpert.util.MyJsonDeserializer;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;

public class RequestDeserializer implements JsonDeserializer<Request> {

	private Class<?> classToDeszerialize;
	private MyJsonDeserializer myJsonDeserializer;

	public RequestDeserializer(Class<?> classToDeszerialize,
			MyJsonDeserializer myJsonDeserializer) {
		this.classToDeszerialize = classToDeszerialize;
		this.myJsonDeserializer = myJsonDeserializer;
	}

	@Override
	public Request deserialize(JsonElement json, Type typeOfT,
			JsonDeserializationContext context) throws JsonParseException {
		JsonObject o = json.getAsJsonObject();
		Request request = new Request();
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
		sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

		String token = o.get("token").getAsString();
		Date requestDate=null;
		try {
			requestDate=sdf.parse(o.get("requestDate").getAsString());
		} catch (ParseException e) {
			throw new JsonParseException(e);
		}

		request.setToken(token);
		request.setRequestDate(requestDate);
		request.setHashKey(o.get("hashKey").getAsString());

		JsonElement jsonElement = o.get("data");
		if (jsonElement != null) {
			request.setData(myJsonDeserializer.deserializeObject(
					jsonElement.toString(), classToDeszerialize));
		}

		return request;
	}

}
